package hendler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"nation-mgr/cache"
	"nation-mgr/model"
	"nation-mgr/pkj"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	redis_key := "error_login_" + username
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if cacheData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}

	var user model.User
	err := model.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.Password != pkj.Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if cacheData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return

}
func RoleNodeAdd(c *gin.Context) {
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := model.RoleNode{
		//Model: gorm.Model{},
		Nid: nid,
		Rid: rid,
	}

	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	/*
	   	SELECT
	        *
	      FROM
	        `roles`
	        LEFT JOIN user_roles ON user_roles.rid = roles.id
	*/

	var roles []model.Role
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.uid= ?", uid).Debug().
		Find(&roles)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": roles,
	})
}
func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
		WHERE
		  role_nodes.rid = 1
	*/
	var nodes []model.Node
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid= ?", rid).Debug().
		Find(&nodes)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": nodes,
	})
}
func GoodAdd(c *gin.Context) {
	good_code := c.PostForm("good_code")
	good_num, _ := strconv.Atoi(c.PostForm("good_num"))
	good_name := c.PostForm("good_name")
	//var Good model.Good
	data := model.Good{
		//Model:    gorm.Model{},
		GoodCode: good_code,
		GoodNum:  good_num,
		GoodName: good_name,
	}
	err := model.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "商品添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "商品添加成功",
	})
}
func GoodOrderAdd(c *gin.Context) {
	gid, _ := strconv.Atoi(c.PostForm("gid"))
	order_code := c.PostForm("order_code")
	order_num, _ := strconv.Atoi(c.PostForm("order_num"))
	data := model.GoodOrder{
		//Model:     gorm.Model{},
		Gid:       gid,
		OrderCode: order_code,
		OrderNum:  order_num,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "商品订单添加成功",
		"data": data,
	})
}
func GoodOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	/*
		SELECT
		  good_orders.order_code AS OrderCode,
		  good_orders.order_num AS OrderNum,
		  goods.good_name AS GoodName,
		  goods.id AS Gid
		FROM
		  `good_orders`
		  LEFT JOIN goods ON good_orders.gid = goods.id
	*/
	var goodOrderList []model.GoodOrderList
	reids_key := "Good_List_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, reids_key).Result()
	if cacheData == "" {
		model.DB.Table("good_orders").Select("good_orders.order_code AS OrderCode",
			"good_orders.order_num AS OrderNum",
			"good_orders.order_price AS OrderPrice",
			"goods.good_name AS GoodName",
			"goods.id AS Gid").
			Joins(" LEFT JOIN goods ON good_orders.gid = goods.id").
			Offset(offset).
			Limit(size).Debug().Find(&goodOrderList)
		jsonData, _ := json.Marshal(&goodOrderList)
		cache.Rdb.Set(cache.Ctx, reids_key, jsonData, time.Second*120)
	} else {
		json.Unmarshal([]byte(cacheData), &goodOrderList)
	}
	var total int64
	model.DB.Model(&model.GoodOrder{}).Debug().Count(&total)
	c.JSON(200, gin.H{
		"code":  500,
		"msg":   "商品订单添加成功",
		"data":  goodOrderList,
		"total": total,
	})
}
func GoodOrderDetail(c *gin.Context) {
	id := c.Query("id")
	var goodOrderList model.GoodOrderList
	reids_key := "Good_List_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, reids_key).Result()
	if cacheData == "" {
		model.DB.Table("good_orders").Select("good_orders.order_code AS OrderCode",
			"good_orders.order_num AS OrderNum",
			"good_orders.order_price AS OrderPrice",
			"goods.good_name AS GoodName",
			"goods.id AS Gid").
			Joins(" LEFT JOIN goods ON good_orders.gid = goods.id").
			Where("good_orders.gid= ?", id).
			Debug().Find(&goodOrderList)
		jsonData, _ := json.Marshal(&goodOrderList)
		cache.Rdb.Set(cache.Ctx, reids_key, jsonData, time.Second*120)
	} else {
		json.Unmarshal([]byte(cacheData), &goodOrderList)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "商品订单添加成功",
		"data": goodOrderList,
	})
}
